﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;
using System.IO;

namespace Gueei.Gallery.Core.Services
{
	public class FileCompressionService : IDisposable
	{
		private readonly string _tempdir;
		public FileCompressionService(string tempDirectory)
		{
			_tempdir = tempDirectory;
		}

		private List<string> _tempWorkingDirectory = new List<string>();

		public IEnumerable<FileInfo> DecompressFiles(byte[] data)
		{
			using (var zip = ZipFile.Read(data))
			{
				// Create temp working directory
				var dirName = Path.Combine(_tempdir, Guid.NewGuid().ToString());
				Directory.CreateDirectory(dirName);
				_tempWorkingDirectory.Add(dirName);

				foreach (var entry in zip.Where(e => !e.IsDirectory))
				{
					var fileName = Path.Combine(dirName, entry.FileName);
					if (Path.GetDirectoryName(fileName) != null)
					{
						Directory.CreateDirectory(Path.GetDirectoryName(fileName));
						using (var fs = File.Create(fileName))
						{
							entry.Extract(fs);
						}
						yield return new FileInfo(fileName);
					}
				}
			}
		}

		public void RemoveAllWorkingDirectories()
		{
			foreach(var dir in _tempWorkingDirectory.ToList())
			{
				Directory.Delete(dir, true);
				_tempWorkingDirectory.Remove(dir);
			}
		}

		public void Dispose()
		{
			// Cleanup all temp directories
			RemoveAllWorkingDirectories();
		}
	}
}
